package com.ymatou.iapi.liveinfo.testcase;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.liveinfo.parameter.SellerActivityBean;
import com.ymatou.iapi.liveinfo.service.SellerActivityCall;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.*;
import com.ymt.utils.tag.*;
import com.ymttest.business.service.LiveCallService;
import com.ymttest.database.mongo.jproduct.LiveProductsWapper;
import com.ymttest.database.mongo.jproduct.LivesWapper;
import com.ymttest.database.mongo.jproduct.ProductsWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;
/**
*买手主页直播列表
*FreeMaker Template自动生成代码
*/
@TestSuite
public class Ts_SellerActivity{
	private static int sellerId ;
	private static String sellerName;
	//此用户为新用户，没有直播相关数据
	private static int sellerId2;
	private static String sellerName2;
	
	private static SellerActivityBean bean;
	private static SellerActivityCall call;
	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("买手主页直播列表");
		try{
		sellerId = Integer.parseInt(EnvSetup.getData("productsellerid"));
		sellerName = EnvSetup.getData("productsellername");
		//此用户为新用户，没有直播相关数据
		sellerId2 = Integer.parseInt(EnvSetup.getData("productsellerid7"));
		sellerName2 = EnvSetup.getData("productsellername7");
		}catch(Throwable e){
			e.printStackTrace();
		}
	}

	@Before
	public void caseUp() {
		bean=new SellerActivityBean();
		call=new SellerActivityCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(call.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_SellerActivity_001() {
		Logger.start(true,"买手主页直播列表-当前卖家id有正在进行的直播且商品数量小于3,IsSingle=true-返回卖家id当前正在进行的直播(商品最多为3个)");
		try {
			Integer lid=LiveCallService.createLiveInProgress(sellerName,sellerId).getJSONObject("Data").getInt("ActivityId");
			LiveCallService.CreateLivesProductByLivesId(sellerId,sellerName,lid,1);
			Thread.sleep(1000); 
		    String cover="http://m.ymatou.com/"+TestDataManager.getRandomUUID().toString();
		    new LivesWapper().updateCover(lid.toString(), cover);
			bean.setSellerId(sellerId);
			bean.setIsSingle(true);
			call.setData(bean);
			call.callService();		
			verifyActivity(bean.getSellerId(),bean.getIsSingle());
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P2.class})
	@TestCase
	public void Tc_SellerActivity_002() {
		Logger.start(true,"买手主页直播列表-当前卖家id有正在进行的直播并且商品数量大于3,IsSingle=true-返回卖家id当前正在进行的直播(商品最多为3个)");
		try {
			Integer lid=LiveCallService.createLiveInProgress(sellerName,sellerId).getJSONObject("Data").getInt("ActivityId");
			for(int i=0;i<4;i++)
			{
			 LiveCallService.CreateLivesProductByLivesId(sellerId,sellerName,lid,1);
			}
			String cover="http://m.ymatou.com/"+TestDataManager.getRandomUUID().toString();
		    new LivesWapper().updateCover(lid.toString(), cover);
			Thread.sleep(1000); 
			
			bean.setSellerId(sellerId);
			bean.setIsSingle(true);
			call.setData(bean);
			call.callService();		
			verifyActivity(bean.getSellerId(),bean.getIsSingle());
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P2.class})
	@TestCase
	public void Tc_SellerActivity_003() {
		Logger.start(true,"买手主页直播列表-当前卖家id有正在进行的直播并且商品数量大于3,IsSingle=false-返回卖家id当前正在进行的直播(商品最多为3个)");
		try {
			int lid=LiveCallService.createLiveInProgress(sellerName,sellerId).getJSONObject("Data").getInt("ActivityId");
			for(int i=0;i<4;i++)
			{
			 LiveCallService.CreateLivesProductByLivesId(sellerId,sellerName,lid,1);
			}
			Thread.sleep(1000); 
			
			bean.setSellerId(sellerId);
			bean.setIsSingle(false);
			call.setData(bean);
			call.callService();		
			verifyActivity(bean.getSellerId(),bean.getIsSingle());
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P2.class})
	@TestCase
	public void Tc_SellerActivity_004() {
		Logger.start(true,"买手主页直播列表-当前卖家id有正在进行的直播,且IsSingle=false-返回卖家id当前正在进行的直播(商品最多为3个)和历史直播");
		try {
			int lid=LiveCallService.createLiveInProgress(sellerName,sellerId).getJSONObject("Data").getInt("ActivityId");
			LiveCallService.CreateLivesProductByLivesId(sellerId,sellerName,lid,1);
			Thread.sleep(1000); 
			
			bean.setSellerId(sellerId);
			bean.setIsSingle(false);
			call.setData(bean);
			call.callService();		
			verifyActivity(bean.getSellerId(),bean.getIsSingle());		
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P2.class})
	@TestCase
	public void Tc_SellerActivity_005() {
		Logger.start(true,"买手主页直播列表-当前卖家id没有正在进行的直播,且IsSingle=true-返回空");
		try {
			LiveCallService.updateLiveDateAsBefore(sellerId);
			Thread.sleep(1000); 
			
			bean.setSellerId(sellerId);
			bean.setIsSingle(true);
			call.setData(bean);
			call.callService();		
		    VerifyIsNull();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P2.class})
	@TestCase
	public void Tc_SellerActivity_006() {
		Logger.start(true,"买手主页直播列表-当前卖家id没有正在进行的直播,且IsSingle=false-返回卖家id历史直播");
		try {
			LiveCallService.updateLiveDateAsBefore(sellerId);
			Thread.sleep(1000); 
			
			bean.setSellerId(sellerId);
			bean.setIsSingle(false);
			call.setData(bean);
			call.callService();		
			verifyActivity(sellerId,false);	
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P3.class})
	@TestCase
	public void Tc_SellerActivity_007() {
		Logger.start(true,"买手主页直播列表-当前卖家id没有正在进行的直播，也没有历史直播,且IsSingle=true-返回空");
		try {
			bean.setSellerId(sellerId2);
			bean.setIsSingle(true);
			call.setData(bean);
			call.callService();		
			VerifyIsNull();		
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@Test
	@Category({P3.class})
	@TestCase
	public void Tc_SellerActivity_008() {
		Logger.start(true,"买手主页直播列表-当前卖家id没有正在进行的直播，也没有历史直播,且IsSingle=false-返回空");
		try {
			bean.setSellerId(sellerId2);
			bean.setIsSingle(false);
			call.setData(bean);
			call.callService();		
			VerifyIsNull();		
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	/**
	 * 1、isSingle=true 不取历史直播，只取当前正在直播，当前没有为空
	 * 2、正在直播的商品 最多3个
	 * 3、历史直播根 lid 倒序
	 * 4、获取历史直播数量 在disconf 配置 10 个
	 * @param sellId
	 * @param isSingle
	 * @throws Exception 
	 */
	private void verifyActivity(int sellId,boolean isSingle) throws Exception
	{
		LivesWapper livesWapper=new LivesWapper();
		LiveProductsWapper liveProductsWapper=new LiveProductsWapper();
		
		ArrayList<Map> livesList=livesWapper.getLivesBySellerId(sellId);
		if(isSingle)//不取历史直播，只取当前正在直播，当前没有为空
		{
            if(livesList.size()>0)
            {
            	ArrayList<Map> liveProducts=liveProductsWapper.getLiveProductsBylid((int)livesList.get(0).get("lid"),3,"{sort:1}");
            	VerifyLives(livesList,0,0);
    			if(liveProducts.size()>0 )
    			{
    			    VerifyProducts(liveProducts,liveProductsWapper);
    			}
            }
            else
            {
            	Logger.verifyEquals("null", call.getData().getString("InProgressActivity"), "验证直播返回数量InProgressActivity是否与mongodb一致");
            }
			Logger.verifyEquals(0, call.GetHistoryActivities().length(), "验证历史直播HistoryActivities是否与mongodb一致");
		}
		else//isSingle=false,显示正在直播（最多3个商品）、历史直播（不带商品）
		{
            if(livesList.size()>0)
            {
            	ArrayList<Map> liveProducts=liveProductsWapper.getLiveProductsBylid((int)livesList.get(0).get("lid"),3,"{sort:1}");
            	VerifyLives(livesList,0,0);
            	if(liveProducts.size()>0 )
    			{
    			    VerifyProducts(liveProducts,liveProductsWapper);
    			}
            }
            else
            {
            	Logger.verifyEquals("null", call.getData().getString("InProgressActivity"), "验证直播返回数量InProgressActivity是否与mongodb一致");
            }
			ArrayList<Map> livesHistoryList=livesWapper.getHistoryLivesBySellerId(sellId,10);
			if(livesHistoryList.size()>0){
				//获取10条历史直播，不带商品
				for(int i=0;i<livesHistoryList.size();i++)
				{
					VerifyLives(livesHistoryList,1,i);
				}
			}else
			{
				Logger.verifyEquals(0, call.GetHistoryActivities().length(), "验证历史直播HistoryActivities是否与mongodb一致");
			}
		}
		Logger.verifyEquals(0, call.GetUpcomingActivities().length(), "验证即将开始直播UpcomingActivities是否与mongodb一致");
	}
	private String GetActivityStatusText(ArrayList<Map> lst,int num,String start1,String end1) throws ParseException, JSONException
	{
		String text="";
		Date currentTime = new Date();

		if((int)lst.get(num).get("action")==1 )
		{
			Calendar calendar  =  new   GregorianCalendar(); 
			calendar.setTime(currentTime); 
			calendar.add(calendar.HOUR,1);
			Date newCurrentTime=calendar.getTime();
			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date start=format.parse(start1);
			Date end=format.parse(end1);
			if((boolean)lst.get(num).get("confirm")==true && ((currentTime.after(start)|| currentTime==start)&& (end.after(currentTime)|| currentTime==end)))
				text="直播中";
			else if((boolean)lst.get(num).get("confirm")==true && start.after(currentTime) && end.after(start))
				text="即将开始";
			else if((boolean)lst.get(num).get("confirm")==false && end.after(newCurrentTime))
				text="未生效";
			else
				text="已结束";
		}
		return text;
	}
	/**
	 * 验证直播的商品
	 * @param livesList
	 * @param searchStatus=0：查询当前正在直播  searchStatus=1：查询已经结束的直播
	 * @param num:直播数量
	 * @throws JSONException
	 * @throws ParseException
	 */
	 private void VerifyLives(ArrayList<Map> livesList,int searchStatus,int num) throws JSONException, ParseException 
	  {
		    int count=num+1;
		    Logger.verifyEquals(200, call.getCode(), "判断code是否为200");
			Logger.verifyEquals("操作成功",call.getMsg(), "判断Msg返回操作成功");
			Logger.verifyEquals(0,call.getBCode(), "判断操作成功时 业务代码是否0");
			Logger.verifyNotNull(call.getServerTime(), "判断服务器时间是否为空");
			Logger.verifyEquals(0, call.getData().getInt("ActivityCount"), "验证直播返回数量ActivityCount是否与mongodb一致");
			if(searchStatus==0){
				VerifyCurrOrHisLives(livesList,0,call.GetInProgressActivity(),"");
			}else
			{
				 JSONObject oHistory=call.GetHistoryActivities().getJSONObject(num);
				VerifyCurrOrHisLives(livesList,num,oHistory,"第"+count+"个历史");
			}
	  }
	 private void VerifyCurrOrHisLives(ArrayList<Map> livesList,int num,JSONObject object,String descStr) throws JSONException, ParseException
	 {
	    Logger.verifyEquals(livesList.get(num).get("title").toString(), object.getString("Title"), "验证"+descStr+"直播title是否与mongodb一致");
		Logger.verifyEquals(livesList.get(num).get("vcover").toString(), object.getString("VideoCover"), "验证"+descStr+"直播VideoCover是否与mongodb一致");
		Logger.verifyEquals(livesList.get(num).get("cover")==null?"null":livesList.get(num).get("cover").toString(), object.getString("LiveCover"), "验证"+descStr+"直播Cover是否与mongodb一致");
		//http://jira.ymatou.cn:8080/browse/JIRACONN-11091
		JSONArray brandslist = object.getJSONArray("Brands");
		for(int i=0;i<brandslist.length();i++){
			String result = brandslist.get(i).toString();
			Logger.verifyIsContains( result,livesList.get(num).get("brands")==null?"null":livesList.get(num).get("brands").toString(), "验证"+descStr+"直播Cover是否与mongodb一致");
//			同步时间不正确，有偏差
//			Logger.verifyEquals(createtime, result.getString("RegisterTime"), result.get("UserId").toString()+"验证RegisterTime");
		}
		
		Logger.verifyEquals(livesList.get(num).get("vurl").toString(), object.getString("VideoUrl"), "验证"+descStr+"直播VideoUrl是否与mongodb一致");
		Logger.verifyEquals(livesList.get(num).get("action").toString().toString(), object.getString("Action").toString(), "验证"+descStr+"直播Action是否与mongodb一致");
		Logger.verifyEquals(livesList.get(num).get("lid").toString(), object.getString("ActivityId").toString(), "验证"+descStr+"直播ActivityId是否与mongodb一致");
		Logger.verifyEquals(livesList.get(num).get("name").toString(), object.getString("ActivityName"), "验证"+descStr+"直播ActivityName是否与mongodb一致");
		Logger.verifyEquals(livesList.get(num).get("pic").toString(), object.getString("ActivityPicture"), "验证"+descStr+"直播ActivityPicture是否与mongodb一致");
		Logger.verifyEquals((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(livesList.get(num).get("add")).toString(), object.getString("AddTime").toString(), "验证"+descStr+"直播AddTime是否与mongodb一致");
		Logger.verifyEquals(livesList.get(num).get("country").toString(), object.getString("Country"), "验证"+descStr+"直播Country是否与mongodb一致");
		Logger.verifyEquals((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(livesList.get(num).get("end")).toString(), object.getString("EndTime"), "验证"+descStr+"直播EndTime是否与mongodb一致");
		Logger.verifyEquals(livesList.get(num).get("sid").toString(), object.getString("SellerId").toString(), "验证"+descStr+"直播SellerId是否与mongodb一致");
		Logger.verifyEquals(livesList.get(num).get("addr").toString(), object.getString("ShopAddress"), "验证"+descStr+"直播ShopAddress是否与mongodb一致");
		Logger.verifyEquals((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(livesList.get(num).get("start")).toString(), object.getString("StartTime"), "验证"+descStr+"直播StartTime是否与mongodb一致");
		Logger.verifyEquals(livesList.get(num).get("content").toString(), object.getString("ActivityInfo"), "验证"+descStr+"直播ActivityInfo是否与mongodb一致");
		String start=(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(livesList.get(num).get("start"));
		String end=(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(livesList.get(num).get("end"));
		Logger.verifyEquals(GetActivityStatusText(livesList,num,start,end), object.getString("ActivityStatusText"), "验证"+descStr+"直播ActivityStatusText是否与mongodb一致"); 
	 }
     //获取直播的商品	
     private void VerifyProducts(ArrayList<Map> liveProducts,LiveProductsWapper liveProductsWapper) throws Exception
	  {
    	ProductsWapper productsWapper=new  ProductsWapper();
		  String spid="";
		  for(int j=0;j<liveProducts.size();j++)
	      {
			JSONObject lpo = new JSONObject(liveProducts.get(j));
			spid=lpo.getString("spid");
			ArrayList<String> plst=productsWapper.getProductsBySpid(spid);
			
			if(plst.size()>0 && call.GetProductList()!=null && call.GetProductList().length()>0)
			{
			for(int n=0;n<plst.size();n++)
			{
			JSONObject pjo = new JSONObject(plst.get(n));
			Logger.verifyEquals(pjo.getBoolean("ispsp"), call.GetProductList().getJSONObject(j).getBoolean("IsPsp"), "验证第"+j+"个直播商品IsPsp是否与mongodb一致");
			Logger.verifyEquals(pjo.getString("spid"), call.GetProductList().getJSONObject(j).getString("ProductId"), "验证第"+j+"个直播商品ProductId是否与mongodb一致");
			Logger.verifyEquals(pjo.getJSONArray("pics").get(0), call.GetProductList().getJSONObject(j).getString("PicUrl"), "验证第"+j+"个直播商品PicUrl是否与mongodb一致");
			//获取最低价格
			String[] mlst=pjo.getString("minp").split(",");
			List<BigDecimal> newmlst = new ArrayList();
			for(int k=0;k<mlst.length;k++)
			{
				 DecimalFormat df = new DecimalFormat("#.0");
				 BigDecimal m=new BigDecimal(mlst[k]);
				if(m.compareTo(new BigDecimal("0.0"))!=0)
					newmlst.add(m);
			}
			Collections.sort(newmlst);
			Logger.verifyEquals(newmlst.get(0).toString(), call.GetProductList().getJSONObject(j).getString("Price"), "验证第"+j+"个直播商品Price是否与mongodb一致");
			Logger.verifyEquals(newmlst.get(0).toString(), call.GetProductList().getJSONObject(j).getString("VipPrice"), "验证第"+j+"个直播商品VipPrice是否与mongodb一致");
			Logger.verifyEquals(newmlst.get(0).toString(), call.GetProductList().getJSONObject(j).getString("NewGuestPrice"), "验证第"+j+"个直播商品NewGuestPrice是否与mongodb一致");
			//LiveProducts 上的 status
			ArrayList<String> lplst=liveProductsWapper.getLivesProductsBySpid(spid);
			if(lplst.size()>0)
			{
				Logger.verifyEquals(new JSONObject(lplst.get(0)).getString("status"), call.GetProductList().getJSONObject(j).getString("SellStatus"), "验证第"+j+"个直播商品SellStatus是否与mongodb一致");
			}
		   }
		  }
	      }
	  }
    private void VerifyIsNull() throws JSONException
    {
    	Logger.verifyEquals(200, call.getCode(), "判断code是否为200");
		Logger.verifyEquals("操作成功",call.getMsg(), "判断Msg返回操作成功");
		Logger.verifyEquals(0,call.getBCode(), "判断操作成功时 业务代码是否0");
		Logger.verifyNotNull(call.getServerTime(), "判断服务器时间是否为空");
		Logger.verifyEquals(0, call.getData().getInt("ActivityCount"), "验证直播返回数量ActivityCount是否与mongodb一致");
		Logger.verifyEquals("null", call.getData().getString("InProgressActivity"), "验证直播返回数量InProgressActivity是否与mongodb一致");
		Logger.verifyEquals(0, call.GetHistoryActivities().length(), "验证直播返回数量HistoryActivities是否与mongodb一致");
		Logger.verifyEquals(0, call.GetUpcomingActivities().length(), "验证即将开始直播UpcomingActivities是否与mongodb一致");
    }
}